package com.maochd.platform.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.maochd.platform.domain.DingTalk;
import com.maochd.platform.domain.Msg2DingTalk;
import com.maochd.platform.domain.TcWebHooks;
import com.maochd.platform.service.DingTalkService;
import com.maochd.platform.service.MsgService;
import lombok.extern.slf4j.Slf4j;
import one.util.streamex.StreamEx;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

@Slf4j
@Service
public class MsgServiceImpl implements MsgService {

    @Resource
    private DingTalkService dingTalkService;

    private static final Map<String, String> STATUS_MAP = new HashMap<String, String>() {
        {
            put("Been Added To The Build Queue", "队列中");
            put("Started", "开始执行");
            put("Success", "成功");
            put("Been Interrupted", "执行中断");
            put("Failed", "执行失败");
        }
    };

    @Override
    public void teamcityAccept(TcWebHooks webHooks) {
        log.info("原始参数:{}", JSON.toJSONString(webHooks));
        List<TcWebHooks.TcEmbeds> embeds = webHooks.getEmbeds();
        TcWebHooks.TcEmbeds hooks = embeds.get(0);
        boolean b = StreamEx.of(STATUS_MAP.entrySet())
                .noneMatch((f) -> hooks.getTitle().startsWith(f.getKey()));
        if (!b) {
            Optional<String> op = StreamEx.of(STATUS_MAP.keySet())
                    .filter((f) -> hooks.getTitle().startsWith(f))
                    .findFirst();
            String title = "暂无标题";
            if (op.isPresent()) {
                title = op.get();
            }
            Map<String, TcWebHooks.TcFields> fieldsMap = StreamEx
                    .of(hooks.getFields())
                    .toMap(TcWebHooks.TcFields::getName, Function.identity());
            TcWebHooks.TcFields branchField = fieldsMap.getOrDefault("Branch", new TcWebHooks.TcFields());
            TcWebHooks.TcFields buildNameField = fieldsMap.getOrDefault("Build Name", new TcWebHooks.TcFields());
            TcWebHooks.TcFields triggeredField = fieldsMap.getOrDefault("Triggered By", new TcWebHooks.TcFields());
            TcWebHooks.TcFields agentField = fieldsMap.getOrDefault("Agent", new TcWebHooks.TcFields());
            TcWebHooks.TcFields projectNameField = fieldsMap.getOrDefault("Project Name", new TcWebHooks.TcFields());
            String branch = branchField.getValue();
            String triggered = triggeredField.getValue();
            String agent = StrUtil.equals("${agentName}", agentField.getValue()) ? "暂无数据" : agentField.getValue();
            String status = STATUS_MAP.get(title);
            String projectName = this.subBetween(projectNameField.getValue(), "[", "]");
            String detail = this.subBetween(buildNameField.getValue(), "(", ")");
            Msg2DingTalk m2t = Msg2DingTalk.builder()
                    .projectName(projectName)
                    .branch(branch).status(status)
                    .triggered(triggered)
                    .agent(agent)
                    .detail(detail)
                    .build();
            DingTalk dt = m2t.dtBuild("deploy", "templates/deploy.md");
            dingTalkService.sendRobot(dt);
        }
    }

    /**
     * 截取
     *
     * @param str 原始字符串
     * @param sp1 截取前缀
     * @param sp2 截取后缀
     * @return str
     */
    private String subBetween(String str, String sp1, String sp2) {
        String s1 = StrUtil.subAfter(str, sp1, false);
        return StrUtil.subBefore(s1, sp2, false);
    }
}
